import cv2
import numpy as np
from getWindow import *

def binarize_image(image_path, threshold_value=127, max_value=255):
    """
    将图像进行二值化处理。
    :param image_path: 输入图像路径
    :param threshold_value: 二值化的阈值，低于该值的像素被设为0，高于该值的像素被设为max_value
    :param max_value: 高于阈值的像素值
    :return: 二值化后的图像
    """
    # 读取图像
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
    if image is None:
        print("[E] 无法加载图像")
        quit()
    # 使用 OpenCV 的二值化函数
    _, binary_image = cv2.threshold(image, threshold_value, max_value, cv2.THRESH_BINARY)
    cv2.imwrite('binarized_image.png', binary_image)
    return binary_image

def get_chess(image_path, template_path, output_image='matched_chess.png'):
    # 检测图像中是否有目标并返回目标地址
    match_location = is_page(image_path, template_path)
    if match_location != -1:
        # 读取原始图像和模板
        screenshot = cv2.imread(image_path)
        top_left = match_location
        template = cv2.imread(template_path)
        template_shape = template.shape[:2]
        bottom_right = (top_left[0] + template_shape[1], top_left[1] + template_shape[0])
        # 绘制矩形框显示匹配结果
        cv2.rectangle(screenshot, top_left, bottom_right, (0, 255, 0), 2)
        # # 保存框选区域的图像
        # cropped_image = screenshot[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]
        cv2.imwrite(output_image, screenshot)
        # 计算底部中心坐标
        bottom_center = (top_left[0] + template_shape[1] // 2, bottom_right[1])
        return bottom_center
    else:
        print("[E] 没有找到匹配的模板")
        return -1

def linear_interpolation(table, distance):
    # 确保表是按照距离排序的
    table.sort(key=lambda x: x[0])
    # 找到给定距离所在的区间
    for i in range(len(table) - 1):
        if table[i][0] <= distance <= table[i+1][0]:
            x1, y1 = table[i]
            x2, y2 = table[i+1]
            break
    else:
        # 如果距离超出表的范围，返回最近的距离对应的时长
        return round(table[-1][1] if distance > table[-1][0] else table[0][1])
    # 使用线性插值公式计算按键时长
    timeDelayMs = y1 + ((distance - x1) * (y2 - y1) / (x2 - x1))
    return round(timeDelayMs)

# D T
table = [
    (100, 460),
    (150, 700),
    (200, 920),
    (250, 1150),
    (300, 1400)
]

if __name__ == "__main__":
        
    # 假设我们要估算距离为175像素的按键时长
    distance = 175
    timeDelayMs = linear_interpolation(table, distance)
    print(f"距离 {distance} 像素对应的按键时长为 {timeDelayMs} 毫秒")
